package com.hmall.trade.Listener;


import com.hmall.api.clients.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.common.utils.UserContext;
import com.hmall.trade.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final IOrderService orderService;

    private final PayClient payClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_QUEUE_NAME),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME, delayed = "true"),
            key = MqConstants.DELAY_ORDER_KEY
    ))
//    监听器执行的是一个新的独立线程，拿不到之前请求头里的用户信息，报错的话在监听器里写上 UserContext.setUser(order.getUserId());
    public void listenerDelayMessage(Long orderId) {
//        UserContext.setUser(order.getUserId());
        //1.查询订单
        Order order = orderService.getById(orderId);
        //2.检测订单状态，判断是否支付
        if (order == null || order.getStatus() != 1) { //订单状态为已支付或关闭
            return;
        }
        UserContext.setUser(order.getUserId());
        //3.未支付，需要查询支付流水
        PayOrderDTO payOrder = payClient.queryPayOrderByBizOrderNo(order.getId());
        //4.判断是否支付成功
        if (payOrder != null && payOrder.getStatus() == 3) {
            //4.1 支付成功，修改订单状态为已支付
            orderService.markOrderPaySuccess(orderId);
        } else {
            //4.2 未支付，修改订单状态为关闭
            orderService.cancelOrder(orderId);
        }
    }
}
